/**
 * Created by Administrator on 2017/9/3 0003.
 */
var todoModel = require('../model/todo'),
    common = require('../../frame/utils/common'),
    _ = require("underscore"),
    TodoBiz = {
        create: function(param){
            var todoParam = {
                todoTitle: param.todoTitle,
                address: param.address,
                startTime: common.parseDate(param.startTime),
                endTime: common.parseDate(param.endTime),
                status: Number(param.status),
                desc: param.desc,
                creator: param.creator,
                createDateTime: new Date()
            };
            return new Promise(function (resolve,reject) {
                todoModel.create(todoParam,function (err,doc) {
                    resolve(err,doc);
                })
            });
        },
        update: function(param){
            var todoParam = {
                startTime: common.parseDate(param.startTime),
                endTime: common.parseDate(param.endTime),
                status: Number(param.status),
                desc: param.desc
            },conditions = {
                _id: param.id
            };
            return new Promise(function (resolve,reject) {
                todoModel.update(conditions,todoParam,{upsert : true},function (err,doc) {
                    resolve(doc);
                });
            });
        },
        findByParam: function(param){
            var queryParam = {
                creator: param.creator
            };

            return new Promise(function (resolve,reject) {
                todoModel.find(queryParam).sort({createDateTime: 'desc'}).exec(function (err,doc) {
                    var arrTodo = _.chain(doc).map(function (todo) {
                        return {
                            id: todo._id.toString(),
                            todoTitle: todo.todoTitle,
                            address: todo.address,
                            status: Number(todo.status),
                            desc: todo.desc,
                            creator: todo.creator,
                            startTime: common.dateFormatter(todo.startTime),
                            endTime: common.dateFormatter(todo.endTime),
                            createDateTime: common.dateFormatter(todo.createDateTime),
                        };
                    }).value();
                    resolve(arrTodo);
                });
            });
        },
        deleteByParam: function (param) {
            var delParam = {
                _id: param.id
            };
            return new Promise(function (resolve,reject) {
                todoModel.remove(delParam,function (err,doc) {
                    resolve(doc);
                });
            });
        }
    };

module.exports = TodoBiz;